package com.soladhoc.annonces.client.ui;

import java.util.ArrayList;

import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;
import com.soladhoc.annonces.client.place.NameTokens;
import com.soladhoc.annonces.client.view.AnnonceListView;
import com.soladhoc.annonces.shared.proxy.AnnonceProxy;
import com.soladhoc.annonces.shared.service.AnnonceRequestFactory.AnnonceService;

public class AnnoncesListPresenter
		extends
		Presenter<AnnonceListView, AnnoncesListPresenter.MyProxy>
		implements AnnoncesUiHandlers {

	private int RANGE = 10;
	private final PlaceManager placeManager;
	private final AnnonceService service;


	@ProxyCodeSplit
	@NameToken(NameTokens.listannonces)
	public interface MyProxy extends ProxyPlace<AnnoncesListPresenter> {
	}

	@Inject
	public AnnoncesListPresenter(final EventBus eventBus,
			final AnnonceListView view, final MyProxy proxy,
			final PlaceManager placeManager, final AnnonceService annonceService) {
		super(eventBus, view, proxy);
		this.placeManager = placeManager;
		this.service = annonceService;
		getView().setUiHandlers(this);
	}

	@Override
	protected void revealInParent() {
		RevealContentEvent
				.fire(this, MainPagePresenter.CENTRAL_SLOT_TYPE, this);
	}

	@Override
	protected void onBind() {
		super.onBind();
	}

	@Override
	public void onDetail(AnnonceProxy annonce) {
		if (annonce != null) {
			PlaceRequest request = new PlaceRequest(NameTokens.annonce).with(
					"title", annonce.getTitle());
			placeManager.revealPlace(request);

		}
	}

	@Override
	protected void onReset() {
		final ArrayList<AnnonceProxy> annonceList = new ArrayList<AnnonceProxy>();
		Request<AnnonceProxy> request = service.fetchRange( 0, RANGE);

		request.fire(new Receiver<AnnonceProxy>() {
			@Override
			public void onSuccess(AnnonceProxy response) {
				annonceList.add(response);
			}
		});

		getView().updateAnnonces(annonceList);
	}
}
